package cn.iocoder.yudao.module.system.service.a_ai.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AIService {

    @Value("${ai.url}")
    private String dl_base_urs;

    //private static String dl_base_urs = "http://10.101.221.237/DL-IVRS";


    /**
     * 视频提取音频流
     *
     * @param path
     * @return
     */
    public String extractAudio(String path) {
        String uri = "/video/extract/acodec/url";
        HttpRequest request = HttpRequest.post(dl_base_urs + uri);
        request.form("video_url", path);
        HttpResponse response = request.execute();
        if (response.isOk()) {
            String result = response.body();
            log.info("video extract srt get tag success!");
            return result;
        } else {
            log.error("video extract srt fail:" + response.body());
            return "";
        }
    }

    public String detectionRemoveFile(String imgFile, Float thresh) {
        String uri = "/detection/remove/file";
        HttpRequest request = HttpRequest.post(dl_base_urs + uri);
        request.form("file", new File(imgFile))
                .form("thresh", thresh);
        HttpResponse response = request.execute();
        if (response.isOk()) {
            String result = response.body();
            JSONObject jsonObject = JSON.parseObject(result);
            int code = jsonObject.getInteger("code");
            if (code == 1) {
                JSONObject re = jsonObject.getJSONObject("result");
                return re.getString("base64");
            }else{
                return "";
            }
        } else {
            return "";
        }
    }

    public String detectionTVLOGO(String videoFrame, Float num) {
        String uri = "/detection/tv/file";
        HttpRequest request = HttpRequest.post(dl_base_urs + uri);
        request.form("file", new File(videoFrame))
                .form("number", num);
        HttpResponse response = request.execute();
        if (response.isOk()) {
            String result = response.body();
            JSONObject jsonObject = JSON.parseObject(result);
            int code = jsonObject.getInteger("code");
            if (code == 1) {
                JSONArray re = jsonObject.getJSONArray("result");
                if (re.size() > 0) {
                    return re.getJSONObject(0).getString("label");
                } else {
                    return "";
                }
            } else {
                return "";
            }
        } else {
            log.error("video detection tv logo fail:" + response.body());
            return "";
        }
    }


    /**
     * 视频字幕提取
     *
     * @param path
     * @return
     */
    public String extractSrt(String path) {
        String uri = "/video/tag/url";
        HttpRequest request = HttpRequest.post(dl_base_urs + uri);
        request.form("video_url", path);
        HttpResponse response = request.execute();
        if (response.isOk()) {
            String result = response.body();
            log.info("video extract srt get tag success!");
            return result;
        } else {
            log.error("video extract srt fail:" + response.body());
            return "";
        }
    }


    /**
     * 图片打标->智能识别武器和天气图,只返回武器图结果
     *
     * @return
     */
    public List<String> imageTag(File file) {
        String uri = "/image/tag/file";
        HttpRequest request = HttpRequest.post(dl_base_urs + uri);
        request.form("file", file);
        HttpResponse response = request.execute();
        if (response.isOk()) {
            String result = response.body();
            log.info("Image get tag success:");
            return getArmyLabel(result);
        } else {
            log.error("Image get tag fail:" + response.body());
            return new ArrayList<>();
        }
    }

    /**
     * 图像特征提取
     *
     * @param file
     * @return
     */
    public String imageFeatures(File file) {
        String uri = "/irs_feature/image/file";
        HttpRequest request = HttpRequest.post(dl_base_urs + uri);
        request.form("file", file);
        HttpResponse response = request.execute();
        if (response.isOk()) {
            String result = response.body();
            JSONObject jsonObject = JSON.parseObject(result);
            int code = jsonObject.getInteger("code");
            if (code == 1) {
                return jsonObject.getJSONObject("result").getString("image_org_feature");
            } else {
                return "";
            }
        } else {
            log.error("image get features fail:" + response.body());
            return "";
        }
    }

    public String insertImage(File file, Long id) {
        String uri = "/insert/image/file";
        HttpRequest request = HttpRequest.post(dl_base_urs + uri);
        request.form("file", file)
                .form("id", id);
        HttpResponse response = request.execute();
        if (response.isOk()) {
            String result = response.body();
            return result;
        } else {
            String result = response.body();
            return result;
        }
    }

    public String searchImage(File file, Long num) {
        String uri = "/irs/img2img/file";
        HttpRequest request = HttpRequest.post(dl_base_urs + uri);
        request.form("file", file)
                .form("show_num", num)
                .form("thresh", 0.6);
        HttpResponse response = request.execute();
        if (response.isOk()) {
            String result = response.body();
            return result;
        } else {
            String result = response.body();
            return result;
        }
    }


    private List<String> getArmyLabel(String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        int code = jsonObject.getInteger("code");
        if (code == 1) {
            JSONObject result = jsonObject.getJSONObject("result");
            JSONArray army = result.getJSONArray("army");
            List<String> list = new ArrayList<>(army.size());
            for (int i = 0; i < army.size(); i++) {
                JSONObject armyObject = (JSONObject) army.get(i);
                list.add(armyObject.getString("label"));
            }
            return list.stream().distinct().collect(Collectors.toList());
        } else {
            log.error("Image get tag fail:" + json);
            return new ArrayList<>();
        }
    }

    public String face(File file) {
        String uri = "/face_recognition/image/file";
        log.debug(dl_base_urs + uri);
        HttpRequest request = HttpRequest.post(dl_base_urs + uri);
        request.form("file", file);
        HttpResponse response = request.execute();
        if (response.isOk()) {
            String result = response.body();
            return result;
        } else {
            throw new ServiceException(501, "人脸识别失败!");
        }
    }

    public String ocr(File pdf) {
        String uri = "/text_ocr/pdf/file";
        log.debug(dl_base_urs + uri);
        HttpRequest request = HttpRequest.post(dl_base_urs + uri);
        request.form("file", pdf);
        HttpResponse response = request.execute();
        if (response.isOk()) {
            String result = response.body();
            JSONObject jsonObject = JSON.parseObject(result);
            log.info(result);
            if (jsonObject.getInteger("code") == 1 || jsonObject.getInteger("code") == 0) {
                return jsonObject.getString("result").replace("http://ai.trs.cn/DL-IVRS", dl_base_urs);
            } else {
                throw new ServiceException(501, "OCR处理失败!");
            }
        } else {
            throw new ServiceException(501, "OCR处理失败!");
        }
    }

    /**
     * 视频人脸提取
     *
     * @param url
     * @return
     */
    public String extractFace(String url) {
        String uri = "/matting/human/video/url";
        log.debug(dl_base_urs + uri);
        HttpRequest request = HttpRequest.post(dl_base_urs + uri);
        request.form("url", url);
        HttpResponse response = request.execute();
        if (response.isOk()) {
            String result = response.body();
            JSONObject jsonObject = JSON.parseObject(result);
            log.info(result);
            if (jsonObject.getInteger("code") == 1 || jsonObject.getInteger("code") == 0) {
                return result;
            } else {
                throw new ServiceException(501, "视频人脸提取失败!");
            }
        } else {
            throw new ServiceException(501, "视频人脸提取失败!");
        }
    }

    //广电节目
    public String broadcast(String path) {
        String uri = "/guangdian/video/file";
        HttpRequest request = HttpRequest.post(dl_base_urs + uri);
        request.form("video_url", path);
        HttpResponse response = request.execute();
        if (response.isOk()) {
            String result = response.body();
            log.info("video extract broadcast get tag success!");
            return result;
        } else {
            log.error("video extract broadcast fail:" + response.body());
            return "";
        }
    }

    /**
     * 语音识别
     *
     * @return
     */
    public String speechAsr(String url, Boolean rec_spk, String return_format, Boolean return_timestamp) {
        if (StringUtils.isBlank(return_format)) {
            return_format = "json";
        }
        String uri = "/speech/asr/url";
        HttpRequest request = HttpRequest.post(dl_base_urs + uri);
        request.form("url", url);
        request.form("rec_spk", rec_spk);
        request.form("return_format", return_format);
        request.form("return_timestamp", return_timestamp);
        HttpResponse response = request.execute();
        if (response.isOk()) {
            String result = response.body();
            System.out.println(result);
            log.info("speech asr success!");
            return result;
        } else {
            log.error("speech asr fail:" + response.body());
            return "";
        }
    }
}
